<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="项目承接人">
              <select-user-by-dep
                placeholder="请选择项目承接人"
                v-model="queryParam.userId"
              />
            </a-form-item>
          </a-col>
          <a-col ::xl="6" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="考核日期">
              <a-month-picker style="width: 100%;" valueFormat = 'YYYY-MM-DD' placeholder="请选择考核日期" picker="month" :allowClear="false" v-model="queryParam.examineTime"  @change="timeChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="newSearchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls(exportTitle)">导出</a-button>
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item,index) in defColumns">
                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                  <a-col :span="12" :key="index"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right;"><a-icon type="setting" :style="iconStyle"/></a>
      </a-popover>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:2000}"
        :components="drag(columns)"
        bordered
        rowKey="id"
        :pagination="ipagination"
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps: (record) => { return { props: { disabled: !record.id } } }}"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <a slot="projectName" slot-scope="text, record" @click="getDetail(record.projectId)">{{ text }}</a>
        <!-- 应收金额 -->
        <span slot="examineCollectMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <a v-else @click="getCapitalAllot(record, 'examineCollectMoney')">{{ text }}</a>
        </span>
        <!-- 实收金额 -->
        <span slot="examineRealCollectMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <a v-else @click="getCapitalAllot(record, 'examineRealCollectMoney')">{{ text }}</a>
        </span>
        <!-- 考核业绩 -->
        <span slot="examineAchievementMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <span v-else>{{ text }}</span>
        </span>
        <!-- 后延一个月回款考核 - 应收金额 -->
        <span slot="lastMonthCollectMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <a v-else @click="getCapitalAllot(record, 'lastMonthCollectMoney')">{{ text }}</a>
        </span>
        <!-- 后延一个月回款考核 - 实收金额 -->
        <span slot="lastMonthRealCollectMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <a v-else @click="getCapitalAllot(record, 'lastMonthRealCollectMoney')">{{ text }}</a>
        </span>
        <!-- 后延一个月回款考核 - 差额 -->
        <span slot="lastMonthDifference" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <span v-else>{{ text }}</span>
        </span>
        <!-- 后延一个月回款考核 - 考核业绩 -->
        <span slot="lastMonthAchievementMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <span v-else>{{ text }}</span>
        </span>
        <!-- 后延两个月的回款考核 - 应收金额 -->
        <span slot="lastSecondMonthCollectMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <a v-else @click="getCapitalAllot(record, 'lastSecondMonthCollectMoney')">{{ text }}</a>
        </span>
        <!-- 后延两个月的回款考核 - 实收金额 -->
        <span slot="lastSecondMonthRealCollectMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <a v-else @click="getCapitalAllot(record, 'lastSecondMonthRealCollectMoney')">{{ text }}</a>
        </span>
        <!-- 后延两个月的回款考核 - 差额 -->
        <span slot="lastSecondMonthDifference" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <span v-else>{{ text }}</span>
        </span>
        <!-- 后延两个月的回款考核 - 考核业绩 -->
        <span slot="lastSecondMonthAchievementMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <span v-else>{{ text }}</span>
        </span>

        <!-- 当月应收考核总计 - 应收金额 -->
        <span slot="totalCollectMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <a v-else @click="getCapitalAllot(record, 'totalCollectMoney')">{{ text }}</a>
        </span>
        <!-- 当月应收考核总计 - 实收金额 -->
        <span slot="totalRealCollectMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <a v-else @click="getCapitalAllot(record, 'totalRealCollectMoney')">{{ text }}</a>
        </span>
        <!-- 当月应收考核总计 - 考核业绩 -->
        <span slot="totalAchievementMoney" slot-scope="text, record">
          <span v-if="record.userName == '合计(元)'">{{ text }}</span>
          <span v-else>{{ text }}</span>
        </span>
      </a-table>
      <!-- 页面使用分页组件 -->
      <!-- <Pagination
        v-if="dataSource && dataSource.length > 0"
        v-model="ipagination.current"
        :total="ipagination.total"
        show-size-changer
        :page-size="ipagination.pageSize"
        @onShowSizeChange="onShowSizeChange"
        :pageSizeOptions="ipagination.pageSizeOptions"
      ></Pagination> -->
    </div>

    <!-- 项目详情开始 -->
    <erp-project-report-modal ref="modalForm"></erp-project-report-modal>
    <!-- 收款金额明细 -->
    <CollectMoneyListItem ref="collectMoney" />
  </a-card>
</template>
<script>
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin';
import { JeecgBpmListMixin } from '@/mixins/JeecgBpmListMixin';
import { mixinDevice } from '@/utils/mixin'
import BusinessCategoryNameSelect from '@views/erp/components/BusinessCategoryNameSelect'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import { getAction } from '@/api/manage';
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import CollectMoneyListItem from './modules/CollectMoneyListItem' // 收款金额明细表
// import Pagination from '@/components/Pagination/Pagination.vue' //引入 Pagination组件
import {tableDragResize} from '@/utils/draggable-multistage'
import moment from 'moment'
export default {
  name: 'ErpAuditCollectMoneyList',
  mixins: [JeecgBpmListMixin, mixinDevice, DisabledAuthFilterMixin,tableDragResize],
  components: {
    ErpProjectReportModal,
    BusinessCategoryNameSelect,
    SelectCompanyInput,
    SelectTeamInput,
    // Pagination,
    SelectUserByDep,
    CollectMoneyListItem
  },
  data() {
    return {
      exportTitle: '禾美集团' + moment().format('YYYY年MM月') + '应收款项目承接人考核结果',
      rowSpanPagination: {
        pageNo: 1,
        pageSize: 5,
        totalPage: 0,
        total: 0
      },

      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      queryParam: {
        reportType: 'undertaker',
        examineTime: moment(new Date()).format('YYYY-MM')
      },
      // 列设置
      settingColumns: [],
      columns: [],
      defColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (text, r, index) {
            return (!text.rowIndex) ? (parseInt(index) + 1) : text.rowIndex;
          }
        },
        { title: '项目承接人',
          dataIndex: 'userName',
          align: 'center',
          width: 200,
          ellipsis: true
        },
        { title: '工号',
          dataIndex: 'workNo',
          align: 'center',
          width: 200,
          ellipsis: true
        },
        // { title: '业务分类',
        //   dataIndex: 'categoryName',
        //   align: 'center',
        //   width: 200,
        //   ellipsis: true
        // },
        // { title: '生产团队',
        //   dataIndex: 'productTeam_dictText',
        //   align: 'center',
        //   width: 200,
        //   ellipsis: true
        // },
        // { title: '项目负责人',
        //   dataIndex: 'projectLeading_dictText',
        //   align: 'center',
        //   width: 200,
        //   ellipsis: true
        // },
        {
          title: '考核期应收账款',
          dataIndex: 'examine',
          children: [
            { title: '应收金额(元)',
              dataIndex: 'examineCollectMoney',
              align: 'center',
              ellipsis: true,
              scopedSlots: { customRender: 'examineCollectMoney' },
              width: 200
            },
            { title: '实收金额(元)',
              dataIndex: 'examineRealCollectMoney',
              align: 'center',
              ellipsis: true,
              scopedSlots: { customRender: 'examineRealCollectMoney' },
              width: 200
            },
            { title: '完成率(%)',
              align: 'center',
              dataIndex: 'examineComplateRate',
              width: 200,
              ellipsis: true
            },
            { title: '考核业绩(元)',
              align: 'center',
              ellipsis: true,
              scopedSlots: { customRender: 'examineAchievementMoney' },
              width: 200,
              dataIndex: 'examineAchievementMoney'
            }
          ]
        },
        {
          title: '后延一个月回款考核',
          dataIndex: 'lastMonth',
          children: [
            { title: '应收金额(元)',
              dataIndex: 'lastMonthCollectMoney',
              align: 'center',
              ellipsis: true,
              scopedSlots: { customRender: 'lastMonthCollectMoney' },
              width: 200
            },
            { title: '实收金额(元)',
              dataIndex: 'lastMonthRealCollectMoney',
              align: 'center',
              ellipsis: true,
              scopedSlots: { customRender: 'lastMonthRealCollectMoney' },
              width: 200
            },
            { title: '差额(元)',
              dataIndex: 'lastMonthDifference',
              align: 'center',
              width: 200,
              scopedSlots: { customRender: 'lastMonthDifference' },
              ellipsis: true
            },
            { title: '考核业绩(元)',
              align: 'center',
              dataIndex: 'lastMonthAchievementMoney',
              scopedSlots: { customRender: 'lastMonthAchievementMoney' },
              width: 200,
              ellipsis: true
            }
          ]
        },
        {
          title: '后延两个月回款考核',
          dataIndex: 'secondMonth',
          children: [
            { title: '应收金额(元)',
              dataIndex: 'lastSecondMonthCollectMoney',
              align: 'center',
              ellipsis: true,
              scopedSlots: { customRender: 'lastSecondMonthCollectMoney' },
              width: 200
            },
            { title: '实收金额(元)',
              dataIndex: 'lastSecondMonthRealCollectMoney',
              align: 'center',
              ellipsis: true,
              scopedSlots: { customRender: 'lastSecondMonthRealCollectMoney' },
              width: 200
            },
            { title: '差额(元)',
              dataIndex: 'lastSecondMonthDifference',
              align: 'center',
              width: 200,
              scopedSlots: { customRender: 'lastSecondMonthDifference' },
              ellipsis: true
            },
            { title: '考核业绩(元)',
              align: 'center',
              dataIndex: 'lastSecondMonthAchievementMoney',
              scopedSlots: { customRender: 'lastSecondMonthAchievementMoney' },
              width: 200,
              ellipsis: true
            }
          ]
        },
        {
          title: '当月应收考核总计',
          dataIndex: 'total',
          children: [
            { title: '应收金额(元)',
              dataIndex: 'totalCollectMoney',
              align: 'center',
              scopedSlots: { customRender: 'totalCollectMoney' },
              ellipsis: true,
              width: 200
            },
            { title: '实收金额(元)',
              dataIndex: 'totalRealCollectMoney',
              scopedSlots: { customRender: 'totalRealCollectMoney' },
              align: 'center',
              ellipsis: true,
              width: 200
            },
            { title: '完成率(%)',
              dataIndex: 'totalComplateRate',
              align: 'center',
              width: 200,
              ellipsis: true
            },
            { title: '考核业绩(元)',
              align: 'center',
              ellipsis: true,
              width: 200,
              scopedSlots: { customRender: 'totalAchievementMoney' },
              dataIndex: 'totalAchievementMoney'
            }
          ]
        }
      ],
      url: {
        c: '/api/erp/project/report/erpProjectReport/queryById',
        list: '/api/erp/project/report/erpReceivableAccountsReportController/undertakerNameList',
        queryProjectReportById: '/api/erp/project/report/erpProjectReport/queryById',
        exportXlsUrl: '/api/erp/project/report/erpReceivableAccountsReportController/exportUndertakerNameNewXls'
      },
      newDataSource:[],
      /* 分页参数 */
      // ipagination: {
      //   current: 1,
      //   pageSize: 10,
      //   pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
      //   showTotal: (total, range) => {
      //     return range[0] + '-' + range[1] + ' 共' + total + '条'
      //   },
      //   showQuickJumper: true,
      //   showSizeChanger: true,
      //   total: 0
      // },
      dictOptions: {},
      // initPageSize: 10
    }
  },
  created() {
    //初始化每页条数
    // this.initPageSize = this.ipagination.pageSize
    this.$set(this.queryParam, 'examineTime', moment(new Date()).format('YYYY-MM'))
    this.exportTitle = '禾美集团' + moment(this.queryParam.examineTime).format('YYYY年MM月')  + '应收款项目承接人考核结果'
    this.columns[3].title = this.getTimeName(this.queryParam.examineTime) + '回款考核'
  },
  methods: {
    async loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      //设置请求的条数为初始值
      // this.ipagination.pageSize = this.initPageSize
      var params = this.getQueryParams();// 查询条件
      params.pageUrl = this.$route.path
      this.loading = true;
      let res = await getAction(this.url.list, params)
      this.loading = false;
      if (res.success) {
        this.dataSource = res.result.list ? res.result.list : []
        // this.ipagination.total = res.result.list ? res.result.list.total : ''
        // 判断是否当前页没有数据且不为第一页
        if (this.dataSource.length == 0 && this.ipagination.current != 1) {
          this.ipagination.current = this.ipagination.current - 1
          this.loadData(this.ipagination.current - 1);
        }
        // 新增一列合计表
        // this.dataHandling(res.result.amount)
        this.tableAddTotalRow()
        // const data = [...this.dataSource];
        // if (this.queryParam.bizTaskType == '1') {
        //   for (var i = 0; i < data.length; i++) {
        //     // item.taskUrge = false;
        //     var item = data[i];
        //     var params = { flowCode: this.flowCode, dataId: item.id };// 查询条件
        //     let res2 = await getAction(this.url.checkNotify, params);
        //     if (res2.result) {
        //       item.taskUrge = true;
        //     }
        //   }
        // }
        // this.dataSource = data;
      } else {
        this.$message.warning(res.message)
      }
      this.bizCount();
    },
    /** 表格增加合计行 */
    tableAddTotalRow() {
      //动态新增每页条数
      // this.ipagination.pageSize = this.initPageSize + 1
      if (this.dataSource.length > 0 && !this.dataSource[this.dataSource.length - 1].id) {
        this.dataSource[this.dataSource.length - 1].userName = '合计(元)'
        this.dataSource[this.dataSource.length - 1].key = 'allAmount'
      }
    },
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      this.filters = {}
      if (Object.keys(filters).length > 0) {
        for (let key in filters) {
          let value = filters[key].join(',')
          if (value) {
            if (key.indexOf('_dictText') != -1) {
              key = key.substring(0, key.indexOf('_dictText'))
            }
            this.filters[key] = value
          }
        }
      }
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination;
      // this.loadData();
    },

    /*如果分页走这个方法*/
    // dataHandling(item) {
    //   //动态新增每页条数
    //   this.ipagination.pageSize = this.initPageSize + 1
    //   var arrs = this.newDataSource
    //   if (arrs.length > 0) {
    //     // let item = {}
    //     item.userName = '合计(元)'
    //     item.key = 'allAmount'
    //     // var amount = 0
    //     // for (let i = 0; i < arrs.length; i++) {
    //     //   amount += arrs[i].amount
    //     // }
    //     // item.amount = amount
    //     this.newDataSource.push(item)
    //   }
    //   this.dataSource = Object.values(this.newDataSource)
    // },
    // 分页改变时调用组件里的方法
    // onShowSizeChange(current, pageSize) {
    //   this.ipagination.current = current
    //   this.ipagination.pageSize = pageSize
    //   //调整每页请求数值
    //   this.initPageSize = this.ipagination.pageSize
    //   this.loadData()
    // },

    timeChange(date) {
      this.columns[3].title = this.getTimeName(date) + '回款考核'
      this.exportTitle = '禾美集团' + moment(this.queryParam.examineTime).format('YYYY年MM月') + '应收款项目承接人考核结果'
    },
    getTimeName(date) {
      const start = moment(date).subtract(2, 'months').startOf('month').format('YYYY-MM-DD')
      const end = moment(date).subtract(2, 'months').endOf('month').format('YYYY-MM-DD')
      const reg = /(\d{4})\-(\d{2})\-(\d{2})/;
      const name = start.replace(reg, '$1年$2月$3日') + '-' + end.replace(reg, '$1年$2月$3日')
      return name
    },
    getDetail(id) {
      const that = this
      this.$nextTick(() => {
        getAction(this.url.queryProjectReportById, { id }).then((res) => {
          if (res.success) {
            const model = res.result
            that.$refs.modalForm.getDetail(model);
            that.$refs.modalForm.title = '项目一览表';
          }
        })
      })
    },
    businessCategoryHandle(obj) {
      if (obj) {
        this.queryParam.categoryCode = obj.categoryCode;
      }
    },
    newSearchReset() {
      this.onClearSelected();
      if (this.bizTaskType) {
        this.queryParam = { bizTaskType: this.bizTaskType };
      }
      this.$set(this.queryParam, 'reportType', 'undertaker')
      this.$set(this.queryParam, 'examineTime', moment(new Date()).format('YYYY-MM'))
      this.columns[3].title = this.getTimeName(this.queryParam.examineTime) + '回款考核'
      this.loadData(1);
    },
    // 点击金额明细
    getCapitalAllot(record, key) {
      // 先清空数据
      this.$refs.collectMoney.type = key || ''
      this.$refs.collectMoney.dataSource = []
      this.$refs.collectMoney.ipagination.total = 0
      // 查询数据
      this.$refs.collectMoney.loading = true
      this.$refs.collectMoney.queryParam.undertaker = record.id
      this.$refs.collectMoney.queryParam.examineTime = this.queryParam.examineTime
      // this.$refs.collectMoney.queryParam.searchMonth = key
      this.$refs.collectMoney.searchReset()

      // 打开弹窗
      this.$refs.collectMoney.visible = true
    }
  }
}
</script>
